import logging
from datetime import datetime

import requests

from Util.DBUtil import DBUtil
from sqlalchemy import text

from Util.request_token_util import get_upm_token_server

# 【标签是否重算-如果当天覆盖量和非当天最后一次执行相差小于0，则认为可能有问题，12点 执行一次、16点执行一次、18点执行一次】

# 手工执行标签接口
tag_service_url = 'https://www.cdp.changan.com.cn/tag-system/api/mergeobject/tag/{}/execute'


def generate_query_sql():
    current_hour = datetime.now().hour
    if current_hour >= 12 and current_hour <= 14:
        calculate_time_condition = "ot.calculate_time <= '12:00'"
    elif current_hour > 16 and current_hour < 18:
        calculate_time_condition = "ot.calculate_time BETWEEN '12:00' AND '16:00'"
    elif current_hour >= 18:
        calculate_time_condition = "ot.calculate_time >= '16:00'"
    else:
        return None  # 如果不符合时间条件，返回 None

    query_sql = (
        "SELECT ot.id FROM ("
        " SELECT tag_id, coverage_varies FROM ( "
        " SELECT tag_id,( t.now_cover_count - t.yest_cover_count ) AS coverage_varies "
        " FROM ("
        " SELECT t1.tag_id, t1.cover_count AS now_cover_count, t2.cover_count AS yest_cover_count "
        " FROM ("
        " SELECT tag_id, cover_count FROM object_modeling_v2.om_tag_exec "
        " WHERE id IN ( SELECT max( id ) id FROM object_modeling_v2.om_tag_exec ote WHERE DATE ( created_dt )= DATE ( now()) GROUP BY tag_id ) "
        " AND exec_status = 300 "
        " ) t1 "
        " INNER JOIN ("
        " SELECT tag_id, cover_count FROM object_modeling_v2.om_tag_exec "
        " WHERE id IN ( SELECT max( id ) id FROM object_modeling_v2.om_tag_exec ote WHERE DATE ( created_dt ) != DATE ( now()) GROUP BY tag_id ) "
        " AND exec_status = 300 "
        " ) t2 ON t1.tag_id = t2.tag_id "
        " ) t "
        " ) t "
        " WHERE coverage_varies <= 0 "
        " ) k "
        " LEFT JOIN object_modeling_v2.om_tag ot ON ot.id = k.tag_id "
        f" WHERE {calculate_time_condition} AND tag_cal_type = 00  and ot.force_update!=1 "
    )

    return query_sql


class TagService:

    def __init__(self):
        pass  # 如果有需要初始化的内容，可以在这里添加

    def tag_error_list(self, db_self):
        query_sql = generate_query_sql()
        if query_sql is None:
            logging.info("Current time does not meet the criteria to run the query.")
            return []

        logging.info(query_sql)
        results = db_self.execute_query(text(query_sql))
        url_list = []  # 创建一个空列表来存储替换后的URL
        if results:
            for row in results:
                tag_id = row[0]  # 获取第一个元素，即 id 列的值
                url = tag_service_url.format(tag_id)  # 使用 format() 方法将 tag_id 插入到 URL 中
                url_list.append(url)  # 将替换后的 URL 添加到列表中
                logging.info(f"Tag ID: {tag_id}, URL: {url}")
        return url_list  # 返回包含所有替换后的 URL 的列表


    def tag_execute(self, urls):
        if not urls:
            logging.info("URL list is empty")
            return
        upm_token_server = get_upm_token_server()
        upm_token = upm_token_server.get_redis_token()
        if not upm_token:
            print("token获取失败")
        else:
            head_map = upm_token.get_head_map()
            cookie_map = upm_token.get_cookie_map()
            for url in urls:
                response = requests.put(url, headers=head_map, cookies=cookie_map, json={})
                print(f"HTTP Response: {response.status_code} {response.text}")




# 运行主函数
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    environment = "prod"
    # 更改为适当的数据库名称
    db_name = "object_modeling_v2"
    db_self = DBUtil(environment, db_name)
    tag_service = TagService()
    url_list = tag_service.tag_error_list(db_self)
    tag_service.tag_execute(url_list)
